package com.lzx.adx.report.util;

import java.io.UnsupportedEncodingException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class UrlParamsReplacer {

    public static String replaceTypeParameter(String originalUrl, String newTypeValue) {
        try {
            String decodedUrl = URLDecoder.decode(originalUrl, "UTF-8");
            String[] urlParts = decodedUrl.split("\\?");

            if (urlParts.length != 2) {
                throw new IllegalArgumentException("Invalid URL format");
            }

            String baseUrl = urlParts[0];
            String query = urlParts[1];
            String[] queryParams = query.split("&");

            StringBuilder newQuery = new StringBuilder();

            for (String param : queryParams) {
                if (param.startsWith("type=")) {
                    newQuery.append("type=").append(URLEncoder.encode(newTypeValue, "UTF-8")).append("&");
                } else {
                    newQuery.append(param).append("&");
                }
            }

            if (newQuery.length() > 0) {
                newQuery.setLength(newQuery.length() - 1); // Remove the trailing '&'
            }

            return baseUrl + "?" + newQuery.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return originalUrl; // Return the original URL on error
        }
    }

    public static void main(String[] args) {
        String originalUrl = "https://ad.ximalaya.com/ad-action?uid=315&timestamp=1583379831565&ip=223.114.125.57&os=android&imei_md5=70de186af7950d9a68a48127de9b6e94&androidid=a14119bfd316c37a&materialid=6021&idfa=IDFA&type=act&invokeid=3388983";
        String newTypeValue = "register";
        String updatedUrl = replaceTypeParameter(originalUrl, newTypeValue);
        System.out.println(updatedUrl);
    }
}
